package com.neusoft.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.neusoft.dto.CommentReq;
import com.neusoft.mapper.ArticlesMapper;
import com.neusoft.mapper.CommentMapper;
import com.neusoft.model.Articles;
import com.neusoft.model.Comments;
import com.neusoft.model.Users;
import com.neusoft.response.ApiResponse;
import com.neusoft.service.impl.CommentService;
import com.neusoft.utils.UserUtils;
import com.neusoft.vo.MultiComments;
import com.neusoft.vo.SingleComment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class CommentController {
    @Autowired
    CommentService commentService;
    @Autowired
    ArticlesMapper articlesMapper;
    @Autowired
    CommentMapper commentMapper;

    @GetMapping("/articles/{slug}/comments")
    public ApiResponse<MultiComments> getComments(@PathVariable("slug") String slug) {
        return ApiResponse.success(commentService.getCommentsByArticleSlug(slug));
    }

    @PostMapping("/articles/{slug}/comments")
    public ApiResponse<SingleComment> addComment(@PathVariable("slug") String slug, @RequestBody CommentReq commentReq) {
        return ApiResponse.success(commentService.addComment(slug, commentReq));
    }

    @DeleteMapping("/articles/{slug}/comments/{id}")
    public void deleteComment(@PathVariable("slug") String slug, @PathVariable("id") Integer authorId) {
        QueryWrapper<Articles> articlesQueryWrapper = new QueryWrapper<>();
        articlesQueryWrapper.eq("slug", slug);
        Articles articles = articlesMapper.selectOne(articlesQueryWrapper);
        Users currentUser = UserUtils.getLoginUser();
        if(authorId == currentUser.getId()) {
            Map<String,Object> map = new HashMap<>();
            map.put("article_id",articles.getId());
            map.put("author_id",authorId);
            articlesMapper.deleteByMap(map);
        }

    }
}
